import { React, useState, useRef } from 'react'
import { useLoginMutation, useRegisterMutation } from '../store/api/authApi';
import { useDispatch } from 'react-redux/es/hooks/useDispatch';
import {login} from '../store/reducer/authSlice'
import { useLocation, useNavigate } from 'react-router-dom';

const AuthForm = () => {
    
    const [isLoginForm, setIsLoginForm] = useState(true);
    const userNameInput = useRef()
    const passwordInput = useRef()
    const emailInput = useRef()

    const [regFn, {error: regError}] = useRegisterMutation()
    const [loginFn, {error: loginError}] = useLoginMutation()
    
    // 获取dispatch
    const dispatch = useDispatch()
    const navigate = useNavigate()
    const location = useLocation()
    const from = location.state?.preLocation?.pathname || '/'
    const submitHandle = (e) => {
        e.preventDefault();
        const username = userNameInput.current.value
        const password = passwordInput.current.value
        if (isLoginForm) {
            loginFn({
                identifier: username,
                password
            }).then(res => {   
                if (!res.error) {
                    console.log(res)
                    // 登录成功 --> 添加标识 标识用户登录状态
                    dispatch(login({
                        token: res.data.jwt,
                        user: res.data.user
                    }))
                    // navigate('/', {replace: true})
                    navigate(from, {replace: true})
                }
            })
        } else {
            const email = emailInput.current.value
            regFn({
                username,
                password,
                email
            }).then(res => {
                if (!res.error) {
                    // 注册成功
                    setIsLoginForm(true)
                }
            })
        }
    }

    return (
        <div>
            <h2>{isLoginForm ? '登录' : '注册'}</h2>
            <p>{isLoginForm && loginError && loginError.data.error.message}</p>
            <p>{!isLoginForm && regError && regError.data.error.message}</p>
            <form onSubmit={submitHandle}>
                <div>
                    <input ref={userNameInput} type="text" placeholder="请输入用户名"></input>
                </div>
                <>
                    {
                        !isLoginForm ?
                            <input ref={emailInput} type="email" placeholder="请输入邮箱"></input>
                            : ''
                    }
                </>
                <div>
                    <input ref={passwordInput} type="password" placeholder="请输入密码"></input>
                </div>
                <div>
                    <button>{isLoginForm ? '登录' : '注册'}</button>
                    <button onClick={
                        (event) => {
                            event.preventDefault()
                            setIsLoginForm(prevState => !prevState)
                        }
                    }>
                        {isLoginForm ? '没有账号，去注册' : '已有账号，去登录'}
                    </button>
                </div>
            </form>
        </div>
    )
}

export default AuthForm